package com.viettel.pon.Tabs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.viettel.pon.R;
import com.viettel.pon.common.CheckConnect;
import com.viettel.pon.common.Constant;
import com.viettel.pon.common.DataBaseHelper;
import com.viettel.pon.common.DialogCommon;
import com.viettel.pon.common.GlobalClass;
import com.viettel.pon.config.Config;

public class UpdateVersion extends Fragment {
	Button btnSyncData;
	TextView txtVersion;
	DialogCommon _dialogCommon;
	Context _context;
	CheckConnect _checkConnect;
	Boolean isConnectionExist = false;
	DataBaseHelper db;
	  ProgressBar pb;
	    Dialog dialog;
	    int downloadedSize = 0;
	    int totalSize = 0;
	    TextView cur_val;
	    int type=0;
	    String url;
	private Logger mLog;
	Button sign_in_button;
	EditText password;
	EditText username;
	DialogCommon _dlg;
	String resultSyncPoles = "";
	GlobalClass _glb;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mLog = Logger.getLogger(UpdateVersion.class);
		View rootView = inflater.inflate(R.layout.activity_update_version, container,
				false);
		btnSyncData = (Button) rootView.findViewById(R.id.btnSyncData);
		db = new DataBaseHelper(getActivity().getApplicationContext());
		_dlg = new DialogCommon(getActivity());
		_context = getActivity().getApplicationContext();
		_glb = (GlobalClass) getActivity().getApplicationContext();
		_checkConnect = new CheckConnect(_context);
		txtVersion=(TextView) rootView.findViewById(R.id.txtVersion);
		try{
			PackageInfo pInfo = null;
			pInfo = _context.getPackageManager().getPackageInfo(_context.getPackageName(), 0);
			String versionName = "-1";
			if (pInfo != null)
				versionName = pInfo.versionName;
			/*
			 * Check version tren server voi version client
			 */
			
			txtVersion.setText("Phiên bản hiện tại:"+versionName+Config.Sub_version);

			}catch(Exception ex){
				ex.printStackTrace();
			}
		btnSyncData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Start Download");
				isConnectionExist = _checkConnect.checkData();
//				if(db.getHouseNotInserted().size()>0 || db.getPlaceNotInserted().size()>0 || db.getRoadNotInserted().size()>0 || db.getPoleNotInserted().size()>0){
//					createDialogErrorNotReturn("Bạn cần đồng bộ dữ liệu trước khi khi update").show();
//				}else{
				if(GlobalClass.pathFile!=null && !"".equals(GlobalClass.pathFile)){
				if (isConnectionExist) {
					  showProgress(url);
	                  new Thread(new Runnable() {
	                      public void run() {
	                           downloadFile(GlobalClass.pathFile);
	                      }
	                    }).start();
				} else {
					createDialogErrorNotReturn("Vui lòng kiểm tra lại kết nối mạng").show();
				}
				}else{
					createDialogErrorNotReturn("Chưa có bản cập nhật mới!").show();
				}
			}
		});
		return rootView;
	}
	String fileName;
	void downloadFile(String dwnload_file_path){
        
        try {
            URL url = new URL(Config.HTTP_WS+dwnload_file_path);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
 
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
 
            //<span id="IL_AD4" class="IL_AD">connect</span>
            urlConnection.connect();
 
            //set the path where we want to save the file           
            String SDCardRoot = Environment.getExternalStorageDirectory()+File.separator+"PON"+File.separator; 
            File file1 = new File(SDCardRoot);
            if (!file1.exists()) {
            	file1.mkdir();
            }
            
            //create a new file, to save the downloaded file 
            fileName = "PONApps";
            
            File file = new File(SDCardRoot,fileName+".apk");
          
            FileOutputStream fileOutput = new FileOutputStream(file);
 
            //Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();
 
            //this is the total size of the file which we are downloading
            totalSize = urlConnection.getContentLength();
 
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    pb.setMax(totalSize);
                }               
            });
             
            //create a buffer...
            byte[] buffer = new byte[10240];
            int bufferLength = 0;
 
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                // update the progressbar //
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        pb.setProgress(downloadedSize);
                        float per = ((float)downloadedSize/totalSize) * 100;
                        cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                    }
                });
            }
            //close the output stream when complete //
            fileOutput.close();
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
//                      pb.dismiss(); // if you want close it..
                	dialog.dismiss();
                	openFile(fileName+".apk");
                }
            });         
         
        } catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);        
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);          
            e.printStackTrace();
        }
        catch (final Exception e) {
            showError("Error : Please <span id=\"IL_AD3\" class=\"IL_AD\">check your internet connection</span> " + e);
        }       
    }
     
    void showError(final String err){
    	getActivity().runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getActivity().getApplicationContext(), err, Toast.LENGTH_LONG).show();
            }
        });
    }
     
    void showProgress(String file_path){
        dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.progressdialog);
        dialog.setTitle("Download <span id=\"IL_AD11\" class=\"IL_AD\">Progress</span>");
 
        TextView text = (TextView) dialog.findViewById(R.id.tv1);
        text.setText("Downloading file from ... " + file_path);
        cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
        cur_val.setText("Starting download...");
        dialog.show();
         
        pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
        pb.setProgress(0);
        pb.setProgressDrawable(getResources().getDrawable(R.drawable.progress_style));  
    }

    
    protected void openFile(String fileName) {
    	File apkFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"PON"+File.separator + fileName);
    	Log.e("hungnd40", Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"PON"+File.separator + fileName);
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    	startActivity(intent);
    }
    
    public AlertDialog createDialogErrorNotReturn(String msg) {
 			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 			builder.setTitle(Constant.MESSAGE_STR.NOTIFY);
 			builder.setMessage(msg);
 			builder.setCancelable(false);
 		
 			builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
 				@Override
 				public void onClick(DialogInterface dialog, int which) {
 				
 				}
 			});
 			AlertDialog dialog = builder.create();
 			return dialog;
 		}
    
}